package cn.itsource.serivce.impl;

import cn.itsource.domain.Role;
import cn.itsource.mapper.PermissionMapper;
import cn.itsource.mapper.RoleMapper;
import cn.itsource.query.RoleQuery;
import cn.itsource.serivce.IRoleService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class RoleServiceImpl implements IRoleService {


    @Autowired
    private RoleMapper roleMapper;

    @Override
    public PageInfo<Role> selectForPage(RoleQuery query) {

        //1.设置第几页 ，每页条数
        PageHelper.startPage(query.getNumber(), query.getPageSize());

        //2.查询列表
        List<Role> list = roleMapper.selectForList(query);

        return new PageInfo(list);
    }

    @Override
    public void insertOrUpdate(Role role) {
        if(role.getId() == null){
            roleMapper.insert(role);
        }else{
            roleMapper.updateById(role);
        }
    }

    /**--------------------------------------------------------
     保存角色和权限的中间表
     1.判断参数
     2.删除当前角色已经关联的权限
     3.把权限字符串通过，逗号切割，变成String[]
     4.批量保存到中间表
     --------------------------------------------------------**/
    @Override
    public void insertRelationWithPermission(Long roleId, String permissionIds) {
        //1.判断参数
        if(roleId == null)throw new RuntimeException("角色ID不可为空");

        //2.删除当前角色已经关联的权限
        roleMapper.deleteRelationWithPermission(roleId);

        if(StringUtils.hasLength(permissionIds)){

            //3.把权限字符串通过，逗号切割，变成List
            String[] perIds = permissionIds.split(",");

            if(perIds != null && perIds.length > 0){
                //3.批量保存到中间表
                roleMapper.insertRelationWithPermission(roleId , perIds);
            }
        }

    }
}
